import { login, getInfo, refreshToken } from '@/api/user.js'

const user = {
  state: {
	phoneNumber: uni.getStorageSync('user_phonenumber_key'),
    token: uni.getStorageSync('user_token_key'),
    name: '',
    avatar: '',
    roles: [],
    permissions: [],
	user: {}
  },

  mutations: {
	SET_PHONE_NUMBER: (state, data) => {
		state.phoneNumber = data
	},
	SET_USER: (state, user)  => {
		state.user = user
	},
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
				uni.login({
					provider: 'weixin',
					success: (res) => {
						login({
							code: res.code,
							loginType: 'OPENID'
						}).then(res2 => {
							if (res2.token) {
								uni.setStorageSync('login_time_key', new Date().getTime())
								uni.setStorageSync('user_token_key', res2.token)
								if (res2.phoneNumber) {
									uni.setStorageSync('user_phonenumber_key', res2.phoneNumber)
									commit('SET_PHONE_NUMBER', res2.phoneNumber)
								}
								if (res2.token) {
									commit('SET_TOKEN', res2.token)
								} else {
									uni.setStorageSync('user_phonenumber_key', null)
								}
								resolve(res2.token)
							} else if (userInfo && userInfo.code) {
								login({
									code: userInfo.code,
									openId: res2.openId
								}).then(res3 => {
									uni.setStorageSync('login_time_key', new Date().getTime())
									uni.setStorageSync('user_token_key', res3.token)
									uni.setStorageSync('user_phonenumber_key', res3.phoneNumber)
									commit('SET_PHONE_NUMBER', res3.phoneNumber)
									commit('SET_TOKEN', res3.token)
									resolve(res3.token)
								}).catch(error => {
									reject(error)
								})
							} else {
								uni.setStorageSync('user_phonenumber_key', null)
								uni.showToast({
									icon: 'none',
									title: '请先登录！'
								})
								reject("登录")
							}
						}).catch(error => {
							reject(error)
						})
					},
					fail: () => {
						reject()
					}
				})
      })
    },
    
    // 刷新令牌
    refreshToken({ commit, state }) {
      return new Promise((resolve, reject) => {
        if (state.token) {
          console.log('Store: 开始刷新令牌')
          refreshToken().then(res => {
            if (res.code === 200) {
              // 更新token
              console.log('Store: 令牌刷新成功')
              uni.setStorageSync('login_time_key', new Date().getTime())
              uni.setStorageSync('user_token_key', res.token)
              commit('SET_TOKEN', res.token)
              resolve(res)
            } else {
              // 刷新失败，触发重新登录
              console.log('Store: 令牌刷新失败，返回错误码', res.code)
              commit('SET_TOKEN', '')
              uni.setStorageSync('user_token_key', null)
              reject(res)
            }
          }).catch(error => {
            // 刷新失败，触发重新登录
            console.log('Store: 令牌刷新请求错误', error)
            commit('SET_TOKEN', '')
            uni.setStorageSync('user_token_key', null)
            reject(error)
          })
        } else {
          console.log('Store: 没有可刷新的令牌')
          reject('没有可刷新的令牌')
        }
      })
    },

    // 退出系统
    logout({ commit }) {
      return new Promise((resolve, reject) => {
        uni.setStorageSync('user_token_key', null)
        commit('SET_TOKEN', '')
        resolve()
      })
    },

    // 获取用户信息
    getUserInfo({ commit, state }) {
      if (state.token) {
        getInfo().then(res => {
          const user = res.user
          const avatar = (user.avatar == "" || user.avatar == null) ? "" : import.meta.env.VITE_APP_BASE_API + user.avatar;
        
          if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', res.roles)
            commit('SET_PERMISSIONS', res.permissions)
          } else {
            commit('SET_ROLES', ['ROLE_DEFAULT'])
          }
          commit('SET_USER', user)
          commit('SET_NAME', user.userName)
          commit('SET_AVATAR', avatar)
        }).catch(error => {
        })
      }
    }
  },
  namespaced: true
}

export default user